package cn.rxls.community.service.impl;

import cn.rxls.community.entity.billEntity.BillOthers;
import cn.rxls.community.dto.goods.AddOrdersGoodsDTO;
import cn.rxls.community.dto.goods.GoodsPageDTO;
import cn.rxls.community.entity.Bill;
import cn.rxls.community.entity.Goods;
import cn.rxls.community.entity.Orders;
import cn.rxls.community.enums.*;
import cn.rxls.community.exception.BusinessException;
import cn.rxls.community.mapper.BillMapper;
import cn.rxls.community.mapper.GoodsMapper;
import cn.rxls.community.mapper.OrdersMapper;
import cn.rxls.community.service.GoodsService;
import cn.rxls.community.util.HttpUtil;
import cn.rxls.community.vo.goods.GoodsVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 商品(Goods)表服务实现类
 *
 * @author makejava
 * @since 2024-06-04 12:05:01
 */
@Service("goodsService")
@Transactional
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private final GoodsMapper goodsMapper;

    private final OrdersMapper ordersMapper;

    private final BillMapper billMapper;

    GoodsServiceImpl(GoodsMapper goodsMapper, OrdersMapper ordersMapper, BillMapper billMapper) {
        this.goodsMapper = goodsMapper;
        this.ordersMapper = ordersMapper;
        this.billMapper = billMapper;
    }

    /**
     * 分页查询上架中的商品
     *
     * @param dto 参数对象
     * @return 多个商品信息
     */
    @Override
    public List<GoodsVO> selectPageByCategory(GoodsPageDTO dto) {
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        return goodsMapper.selectPageGoodsByCategory(dto.getPage(), dto.getSize(), dto.getId(), GoodsStateEnum.NORMAL.code);
    }

    /**
     * 根据id查询详情数据
     *
     * @param id 商品主键id
     * @return 单条数据
     */
    @Override
    public GoodsVO selectDetail(Long id) {
        return goodsMapper.selectDetail(id);
    }

    /**
     * 商品购买
     *
     * @param dto 参数对象
     * @return 订单id
     */
    @Override
    public Long purchaseGoods(AddOrdersGoodsDTO dto) {
        //获取用户信息
        String uid = String.valueOf(HttpUtil.getUserLoginInfo().get("uid"));

        //查询到的商品信息
        Goods info = goodsMapper.selectById(dto.getId());
        Optional.ofNullable(info).orElseThrow(() -> new BusinessException(ResultEnum.ERROR_GOODS));

        //库存是否足够
        if (info.getGoodsInventory() >= dto.getNum()) {
            //扣减库存-乐观锁
            Integer integer = goodsMapper.inventoryDeductions(dto.getId(), dto.getNum(), info.getGoodsInventory());
            if (integer < 1) {
                throw new BusinessException(ResultEnum.ERROR_GOODS_INVENTORY);
            }
        }

        //创建商品订单
        Orders orders = new Orders();
        orders.setOrdersMsg(info.getGoodsTitle());
        orders.setProductsNum(dto.getNum());
        orders.setOrdersCategory(OrdersTypeEnum.ORDERS_GOODS.msg);
        orders.setOrdersState(OrdersStateEnum.WARN_PAY.code);
        orders.setUserId(Long.valueOf(uid));
        orders.setProductsId(dto.getId());
        if (ordersMapper.insert(orders) < 1) {
            throw new BusinessException(ResultEnum.ERROR_ORDERS_GOODS);
        }

        //创建账单
        Bill bill = new Bill();
        bill.setBillCategory(BillTypeEnum.OTHERS.msg);
        bill.setBillUser(Long.valueOf(uid));
        bill.setBillMsg(info.getGoodsTitle());
        bill.setBillState(BillStateEnum.WARN_PAY.code);
        bill.setBillPrice(info.getGoodsPrice() * dto.getNum());
        BillOthers billInfo = new BillOthers();
        billInfo.setNum(dto.getNum());
        billInfo.setUnivalent(info.getGoodsPrice() > 0 ? info.getGoodsPrice() : info.getGoodsDiscount());
        bill.setBillSpecifics(JSON.toJSONString(billInfo));
        if(billMapper.insert(bill) <1){
            throw new BusinessException(ResultEnum.ERROR_ADD_BILL);
        }
        return orders.getOrdersId();
    }
}

